package com.example.partner.adapter.user;

import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.CheckBox;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.partner.R;

import java.util.ArrayList;

public class TagsAdapter extends RecyclerView.Adapter<TagsAdapter.ViewHolder> {
    private String[] tags;
    private ArrayList<String> selectedTags = new ArrayList<>();

    public TagsAdapter(String[] tags) {
        this.tags = tags;
    }

    public interface OnTagSelectedListener {
        void onTagSelected(ArrayList<String> selectedTags);
    }

    private OnTagSelectedListener listener;

    public void setOnTagSelectedListener(OnTagSelectedListener listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        CheckBox checkBox = (CheckBox) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_tag, parent, false);
        return new ViewHolder(checkBox);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        String tag = tags[position];
        holder.checkBox.setText(tag);
        holder.checkBox.setOnCheckedChangeListener(null); // 避免触发旧的监听器
        holder.checkBox.setChecked(selectedTags.contains(tag));

        holder.checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                selectedTags.add(tag);
            } else {
                selectedTags.remove(tag);
            }
            if (listener != null) {
                listener.onTagSelected(selectedTags);
            }
        });
    }

    @Override
    public int getItemCount() {
        return tags.length;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        CheckBox checkBox;

        public ViewHolder(CheckBox checkBox) {
            super(checkBox);
            this.checkBox = checkBox;
        }
    }

    public ArrayList<String> getSelectedTags() {
        return selectedTags;
    }
}
